<template>
  <div class="updategender-container">
    <van-picker
      show-toolbar
      :columns="columns"
      :default-index="defaultIndex"
      @cancel="$emit('close')"
      @confirm="onConfirm"
      @change="onGenderChange"
    />
  </div>
</template>
<script>
import { editUserProfile } from '@/api/user'
export default {
  name: 'updateGender',
  data () {
    return {
      // 选择框数组
      columns: ['男', '女'],
      // 默认选择项
      defaultIndex: this.value
    }
  },
  props: {
    value: {
      type: Number,
      required: true
    }
  },
  methods: {
    // 选择框的change事件
    onGenderChange (picker, value, index) {
      this.defaultIndex = index
    },
    // 确定修改性别
    async onConfirm () {
      // 保存提示
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })

      // 调用接口, 修改性别
      await editUserProfile({
        gender: this.defaultIndex
      })

      // 修改成功, 提示
      this.$toast.success({
        message: '保存成功',
        forbidClick: true
      })
      // 向父组件发射自定义方法, 修改父组件性别
      this.$emit('input', this.defaultIndex)
      // 向父组件发射自定义方法, 关闭弹层
      this.$emit('close')
    }
  }
}
</script>
<style lang="less">
</style>
